#!/usr/bin/python
#-*- coding: utf-8 -*-

from core.AbstractChecker import AbstractChecker
import zipfile

class SignatureChecker(AbstractChecker):
    def __init__(self, signature):
        self.signature = signature

    def unzipCert(zipfilename, unziptodir):
        if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
        zfobj = zipfile.ZipFile(zipfilename)
        for name in zfobj.namelist():
            name = name.replace('\\','/')
            
            if name.endswith('/'):
                pass #os.mkdir(os.path.join(unziptodir, name))
            else:            
                if name.lower().endswith('CERT.RSA'.lower()):
                    ext_filename = os.path.join(unziptodir, name)
                    ext_dir= os.path.dirname(ext_filename)
                    if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
                    outfile = open(ext_filename, 'wb')
                    outfile.write(zfobj.read(name))
                    outfile.close()
                    return ext_filename
        return ''

    def check(self, filePath, report):
        cert = unzipCert(filePath, tmpDir)
        if cert != '':
            # if 'linux' in CURRENT_PLATFORM:
            infos = execShell('%s -printcert -file %s' % ('keytool', cert))
            for line in infos:
                value  =line.strip('\r\n').upper()
                if 'SHA1' in value:
                    kv = value.split(': ')
                    sha1 = kv[1].replace(':','').upper()
                    if SKY_SIGNATURE_SHA1 == sha1:
                        report.addReport(report.setHeader(3, report.setDangerous('useSignature: true')))
                        os.remove(cert)
                        return report
        report.addReport(report.setHeader(3,'useSignature: false'))
        if cert != '':
            os.remove(cert)
        return report
